package com.szbmyoubao.app.ui.login.pay

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import com.szbmyoubao.app.timer.tickFlow
import com.szbmyoubao.app.ui.login.forget.UpdateSuccessActivity
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.ktx.load
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.databinding.ActivityPayPwdBinding
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 *@author joe
 *@data 2024/10/29
 *@describe
 */
class PayPwdActivity : BaseMvvmActivity<ActivityPayPwdBinding, PayPwdViewModel>(),
    View.OnClickListener {
    override val userBaseTitle: Boolean
        get() = false
    private var mTickJob: Job? = null

    companion object {
        fun launch(context: Context) {
            context.startActivity(
                Intent(context, PayPwdActivity::class.java)
            )
        }
    }

    override fun inflateBinding(): ActivityPayPwdBinding =
        ActivityPayPwdBinding.inflate(layoutInflater)

    override fun initialize(savedInstanceState: Bundle?) {
    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is PayPwdState.SmdCodeSuccess -> {
                    ToastUtils.show("验证码已发送")
                    countDown()
                }
                is PayPwdState.PayPwdSuccess -> {
                    UpdateSuccessActivity.Companion.launch(this)
                    finish()
                }
                is PayPwdState.GetPicCodeSuccess -> {
                    binding.ivPicCode.load(this, it.url)
                }
            }
        }
    }

    override fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(true)
            titleBar(binding.toolBar)
        }
    }

    override val darkFont: Boolean
        get() = false

    override fun initEvent() {
        binding.etPhone.addTextChangedListener(textWatch)
        binding.ivEye.setOnClickListener(this)
        binding.ivReEye.setOnClickListener(this)
        binding.tvSendTitle.setOnClickListener(this)
        binding.tvConfirm.setOnClickListener(this)
        binding.toolBar.setNavigationOnClickListener { finish() }
        binding.ivPicCode.setOnClickListener(this)
    }

    private val textWatch = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable?) {
            if (!s.isNullOrEmpty() && s.toString().length == 11) {
                binding.layoutPicCode.visibility = View.VISIBLE
                lifecycleScope.launch {
                    viewModel.intentChannel.send(PayPwdIntent.GetPicCode(s.toString()))
                }
            } else {
                binding.layoutPicCode.visibility = View.GONE
            }
        }

    }


    override fun initData() {
    }

    /**
     * 密码是否可见
     * 1 明文
     */
    private fun setEysSee(editText: EditText, imageView: ImageView) {
        logD("type=${editText.inputType}")
        if (editText.inputType == 1) {
            editText.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT
        } else {
            editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_NORMAL
        }
        setSye(imageView, editText.inputType == 1)
        //光标位置
        editText.setSelection(editText.text.toString().length)
    }

    private fun setSye(imageView: ImageView, isSee: Boolean) {
        imageView.setImageResource(if (isSee) R.mipmap.icon_eye_open else R.mipmap.icon_eye_close)
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.iv_eye -> {
                setEysSee(binding.etPassword, binding.ivEye)
            }
            R.id.iv_re_eye -> {
                setEysSee(binding.etRePassword, binding.ivReEye)
            }
            R.id.tv_send_title -> {
                val imagCode = binding.etPicCode.text.toString().trim()
                val phone = binding.etPhone.text.toString().trim()
                lifecycleScope.launch {
                    viewModel.intentChannel.send(PayPwdIntent.SendSmsCode(imagCode, phone))
                }
            }
            R.id.tv_confirm -> {
                toForget()
            }
            R.id.iv_pic_code -> {
                val phone = binding.etPhone.text.toString().trim()
                lifecycleScope.launch {
                    viewModel.intentChannel.send(PayPwdIntent.GetPicCode(phone))
                }

            }
        }
    }

    private fun toForget() {
        val phone = binding.etPhone.text.toString().trim()
        val psw = binding.etPassword.text.toString().trim()
        val rePsw = binding.etRePassword.text.toString().trim()
        val code = binding.etSmsCode.text.toString().trim()

        lifecycleScope.launch {
            viewModel.intentChannel.send(PayPwdIntent.PayPwdPwd(code, psw, rePsw, phone, 2))
        }
    }


    // (函数)，开始倒计时
    private fun countDown() {
        var duration = 60
        mTickJob?.cancel()
        mTickJob = tickFlow {
            duration -= 1
            if (duration <= 0) {
                mTickJob?.cancel()
                // 结束
                binding.tvSendTitle.text = "发送验证码"
                binding.tvSendTitle.isEnabled = true
            } else {
                binding.tvSendTitle.text = "${duration}后重发"
                binding.tvSendTitle.isEnabled = false
            }
        }
    }

    override fun onDestroy() {
        binding.etPhone.removeTextChangedListener(textWatch)
        super.onDestroy()
    }
}